package com.CmJava.crowd.service.imp;

import com.CmJava.crowd.entity.CrowdException;
import com.CmJava.crowd.entity.ResultEntity;
import com.CmJava.crowd.entity.Admin;
import com.CmJava.crowd.entity.AdminExample;
import com.CmJava.crowd.mapper.AdminMapper;
import com.CmJava.crowd.entity.Md5Util;
import com.CmJava.crowd.service.AdminService;
import com.CmJava.crowd.service.EmailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private EmailService emailService;


    @Override
    public void addAdmin(Admin admin) throws Exception{
        // 设置查询条件
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andAdminaccountEqualTo(admin.getAdminaccount());
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        if (admins.size()==0) {
            adminMapper.insert(admin);
        }else {
            throw new RuntimeException("该用户已存在，不可重复登陆");
        }
    }

    @Override
    public Admin findAdmin(String adminAccount, String adminPassword) {
        // 设置查询条件
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andAdminaccountEqualTo(adminAccount);
        // 以管理员账号来查数据库
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        // 查不到，账号不存在，登陆失败
        if (admins.size()==0){
            throw new CrowdException(CrowdException.USERACCOUNT_EXCEPTION);
        }
        Admin admin = admins.get(0);
        // 查出多个数据，数据库有误 ;admin为null，数据封装出问题；未知错误
        if (admins.size()>1 || admin==null){
            throw new CrowdException(CrowdException.UNDEFINED_EXCEPTION);
        }
        String adminPasswordSql = admin.getAdminpassword();
        // 表单密码的md5和数据库密码md5不匹配，登陆失败
        if( !Md5Util.md5(adminPasswordSql).equals(Md5Util.md5(adminPassword))){
            throw new CrowdException(CrowdException.ACCESS_EXCEPTION);
        }
        return admin;

    }

    @Override
    public PageInfo<Admin> adminList(int cp, int pageNum, String keyWord) {
        // 开启分页功能
        PageHelper.startPage(cp,pageNum);
        List<Admin> admins = adminMapper.adminList(keyWord);
        // 封装到PageInfo中
        PageInfo<Admin> adminPageInfo = new PageInfo<>(admins);
        return adminPageInfo;
    }

    @Override
    public ResultEntity deleteAdminByList(ArrayList<String> primaryKeyList) {
        try {
            for (String s : primaryKeyList) {
                adminMapper.deleteByPrimaryKey(Integer.parseInt(s));
            }
        }catch (Exception e){
            return ResultEntity.failWithoutMessage();
        }
        return ResultEntity.successWithoutData();
    }

    @Override
    public ResultEntity deleteOneAdmin(String primaryKey) {
        int i=0;
        i = adminMapper.deleteByPrimaryKey(Integer.parseInt(primaryKey));
        if (i!=1){
            return ResultEntity.failWithoutMessage();
        }
        return ResultEntity.successWithoutData();
    }

    @Override
    public ResultEntity findOneAdmin(String primaryKey) {
        Admin admin =null;
        admin= adminMapper.selectByPrimaryKey(Integer.parseInt(primaryKey));
        if (admin!=null) {
            return ResultEntity.successWithData(admin);
        }
        return ResultEntity.failWithoutMessage();
    }

    @Override
    public ResultEntity updateOneAdmin(Admin admin) {
        //updateByPrimaryKeySelective会对字段进行判断再更新(如果为Null就忽略更新)。
        // updateByPrimaryKey对你注入的字段全部更新
        int i=0;
        i = adminMapper.updateByPrimaryKeySelective(admin);
        if (i!=1){
            return ResultEntity.failWithoutMessage();
        }
        return ResultEntity.successWithoutData();
    }

    @Override
    public ResultEntity forgotPassword(String adminAccount,String email) {
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andAdminaccountEqualTo(adminAccount);
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        if (admins.size()==1 && admins.get(0)!=null){
            String email1 = admins.get(0).getEmail();
            if (!email1.equals(email)){
                return ResultEntity.failWithoutMessage();
            }else {
                String uuid = UUID.randomUUID().toString().replaceAll("-","");
                Admin admin = admins.get(0);
                admin.setAdminpassword(uuid);
                ResultEntity resultEntity=ResultEntity.successWithData(admin);
                // 以后我的qq邮箱授权码变了，这边要改
                try {
                    emailService.sendTextEmail("2424847652@qq.com", "nyzbmoigqqolebjd",
                            email, "找回密码邮件", "您的新密码是:" + uuid + "，请及时更改您的密码...");
                } catch (MessagingException e) {
                    return ResultEntity.failWithoutMessage();
                }finally {
                    return resultEntity;
                }
            }
        }
        return null;
    }
}
